package controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *实现用户信息显示
 * Created with IntelliJ IDEA.
 * User:xieChao
 * Date:2022/12/5 20:50
 */
@WebServlet("/authorInfo")
public class AuthorServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf8");
        //通过这个方法获取作者信息
        String param = req.getParameter("blogId");
        if(param == null || "".equals(param)){
            //参数缺少
            resp.getWriter().write("{\"ok\": false, \"reason\": \"参数缺失!\"}");
            return;
        }
        //根据当前的blogId在数据库查找，找到对应的blog对象，进而根据blog对象，找到作者信息
        BlogDao blogDao = new BlogDao();
       Blog blog = blogDao.selectOne(Integer.parseInt(param));
       if(blog == null){
           resp.getWriter().write("{\"ok\": false, \"reason\": \"此博客不存在!\"}");
           return;
       }
       //根据blog对象，查找到用户对象
        UserDao userDao = new UserDao();
      User author = userDao.selectById(blog.getUserId());
      if(author == null){
          resp.getWriter().write("{\"ok\": false, \"reason\": \"该用户不存在!\"}");
          return;
      }
      //把author返回浏览器
        //把密码给去掉
        author.setPassword("");
        resp.getWriter().write(objectMapper.writeValueAsString(author));
    }
}
